package com.mc.moring.information;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.google.gson.Gson;
import com.mc.moring.app.LogUtils;
import com.mc.moring.base.HttpCallback;
import com.mc.moring.bean.GetFullUserBean;
import com.mc.moring.bean.ZiLiPageUserDataBean;
import com.mc.moring.information.fragment.FamilialInformationFragment;
import com.mc.moring.information.fragment.LaboralInformationFragment;
import com.mc.moring.information.fragment.LinkAccountFragment;
import com.mc.moring.information.fragment.PersonalInformationFragment;
import com.mc.moring.R;
import com.mc.moring.base.BaseActivity;
import com.mc.moring.information.modle.KycModle;
import com.mc.moring.main.MainActivity;
import com.mc.moring.util.PointMgr;
import com.mc.moring.util.T;
import com.mc.moring.widge.CommonRetentionDialog;
import com.mc.moring.widge.LoadingDialog;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class CapitalInforActivity extends BaseActivity implements LaboralInformationFragment.ActivityListener, FamilialInformationFragment.ActivityListener, LinkAccountFragment.ActivityListener {
    public final int TAG_INDEX_ONE = 0;
    public final int TAG_INDEX_TWO = 1;
    public final int TAG_INDEX_THREE = 2;
    public final int TAG_INDEX_FOUR = 3;

    private final String FRAGMENTNAMEONE = "fragmentOne";
    private final String FRAGMENTNAMETWO = "fragmentTwo";
    private final String FRAGMENTNAMETHREE = "fragmentThree";
    private final String FRAGMENTNAMEFOUR = "fragmentFour";
    private FragmentManager fragmentManager;

    private PersonalInformationFragment personalInformation;
    private LaboralInformationFragment laboralInformation;
    private FamilialInformationFragment familialInformation;
    private LinkAccountFragment linkAccount;
    private TextView headerTitle;

    private LinearLayout dialog_background;

    FrameLayout mFlSafety;
    ImageView mIvSafetyClose;

    TextView mTvSafety;
    TextView mTvBancarias;
    TextView mTvFamiliares;
    TextView mTvLaborales;
    TextView mmTvPersonales;
    FrameLayout mFlBaseView;

    CommonRetentionDialog retentionDialog, linkCommonRententionDialog;

    public KycModle kycModle = null;
    private int tabIndex = 0;
    private String from = "";

    public String a = "ss";


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_capital_infor);
        PointMgr.INSTANCE.sendEvent("cl_personal_info_open");
        Log.e("PointMgr.INSTANCE.sendEvent","cl_personal_info_open");
        from = getIntent().getStringExtra("_from");

        if (savedInstanceState != null && fragmentManager != null) {
            if (fragmentManager.findFragmentByTag(FRAGMENTNAMEONE) != null) {
                personalInformation = (PersonalInformationFragment) fragmentManager.findFragmentByTag(FRAGMENTNAMEONE);
            }
            if (fragmentManager.findFragmentByTag(FRAGMENTNAMETWO) != null) {
                laboralInformation = (LaboralInformationFragment) fragmentManager.findFragmentByTag(FRAGMENTNAMETWO);
            }
            if (fragmentManager.findFragmentByTag(FRAGMENTNAMETHREE) != null) {
                familialInformation = (FamilialInformationFragment) fragmentManager.findFragmentByTag(FRAGMENTNAMETHREE);
            }
            if (fragmentManager.findFragmentByTag(FRAGMENTNAMEFOUR) != null) {
                linkAccount = (LinkAccountFragment) fragmentManager.findFragmentByTag(FRAGMENTNAMEFOUR);
            }
        }
        kycModle = KycModle.Companion.getInstant();
        init();

    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void initView() {

        fragmentManager = getSupportFragmentManager();
        mFlSafety = findViewById(R.id.fl_safety);
        mTvSafety = findViewById(R.id.tv_safety);
        mIvSafetyClose = findViewById(R.id.iv_safety_close);
        dialog_background = findViewById(R.id.dialog_background);
        mTvBancarias = findViewById(R.id.tv_bancarias);
        mTvFamiliares = findViewById(R.id.tv_familiares);
        mTvLaborales = findViewById(R.id.tv_laborales);
        mmTvPersonales = findViewById(R.id.tv_personales);
        mFlBaseView = findViewById(R.id.fl_base_view);
        headerTitle = findViewById(R.id.header_title_text);
        retentionDialog = new CommonRetentionDialog(this);
        linkCommonRententionDialog = new CommonRetentionDialog(this);

        retentionDialog.setDialogViewOnClickListener(new CommonRetentionDialog.DialogViewOnClickListener() {
            @Override
            public void onClickConfirm() {

            }

            @Override
            public void onClickCancel() {
                finish();
            }
        });

        linkCommonRententionDialog.setDialogViewOnClickListener(new CommonRetentionDialog.DialogViewOnClickListener() {
            @Override
            public void onClickConfirm() {
            }

            @Override
            public void onClickCancel() {
                if (!TextUtils.isEmpty(from)) {
                    finish();
                    startActivity(MainActivity.class);
                } else {
                    CapitalInforActivity.this.finish();
                }
            }
        });
        mIvSafetyClose.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                // kelvin
                if (mFlSafety.getVisibility() == View.VISIBLE) {
                    mFlSafety.setVisibility(View.GONE);
                }
                if (mIvSafetyClose.getVisibility() == View.VISIBLE) {
                    mIvSafetyClose.setVisibility(View.GONE);
                }
            }
        });
        Map<String, String> params = new HashMap<String, String>();
        params.put("custId", ZiLiPageUserDataBean.getInstance().getCustomerId());
//        doTab(TAG_INDEX_TWO);
//        tabIndex=1;
        showLoading();
        kycModle.getZiLiPageUserFullInfo(params, new HttpCallback() {
            @Override
            public void onSuccess(@NonNull String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if (kycModle.isSuccess(jsonObject)) {
                        GetFullUserBean bean = new Gson().fromJson(data, GetFullUserBean.class);
                        if (bean.getData().getItemInputStatus().getUserInfoStatus() == 1
                                && bean.getData().getItemInputStatus().getWorkInfoStatus() == 1
                                && bean.getData().getItemInputStatus().getInfoStatus() == 1) {
                            doTab(TAG_INDEX_FOUR);
                            tabIndex = 3;
                            return;
                        }
                        if (bean.getData().getItemInputStatus().getUserInfoStatus() == 1
                                && bean.getData().getItemInputStatus().getWorkInfoStatus() == 1) {
                            doTab(TAG_INDEX_THREE);
                            tabIndex = 2;
                            return;
                        }
                        if (bean.getData().getItemInputStatus().getUserInfoStatus() == 1) {
                            doTab(TAG_INDEX_TWO);
                            tabIndex = 1;
                            return;
                        }
                        onTabSelected(TAG_INDEX_ONE);
                    } else {
                        T.showShort(getActivity(), kycModle.getStringToJson(jsonObject, "msg"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                hideLoading();
            }

            @Override
            public void onFaill(@NonNull String e) {
                hideLoading();
            }

        });
    }

    private void doTab(int tab) {
        LogUtils.logE("tabIndex2>>>" + tabIndex);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (tab == TAG_INDEX_FOUR) {
                    onTabSelected(TAG_INDEX_FOUR);
                    mmTvPersonales.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_complete));
                    mmTvPersonales.setTextColor(getActivity().getColor(R.color.black));
                    mTvLaborales.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_complete));
                    mTvLaborales.setTextColor(getActivity().getColor(R.color.black));
                    mTvFamiliares.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_complete));
                    mTvFamiliares.setTextColor(getActivity().getColor(R.color.black));
                    mTvBancarias.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_complete));
                    mTvBancarias.setTextColor(getActivity().getColor(R.color.black));
                } else if (tab == TAG_INDEX_THREE) {
                    onTabSelected(TAG_INDEX_THREE);
                    mmTvPersonales.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_complete));
                    mmTvPersonales.setTextColor(getActivity().getColor(R.color.black));
                    mTvLaborales.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_complete));
                    mTvLaborales.setTextColor(getActivity().getColor(R.color.black));
                    mTvFamiliares.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_complete));
                    mTvFamiliares.setTextColor(getActivity().getColor(R.color.black));
                    mTvBancarias.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_not_completed));
                    mTvBancarias.setTextColor(Color.parseColor("#999999"));
                } else if (tab == TAG_INDEX_TWO) {
                    onTabSelected(TAG_INDEX_TWO);
                    mmTvPersonales.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_complete));
                    mmTvPersonales.setTextColor(getActivity().getColor(R.color.black));
                    mTvLaborales.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_complete));
                    mTvLaborales.setTextColor(getActivity().getColor(R.color.black));
                    mTvFamiliares.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_not_completed));
                    mTvFamiliares.setTextColor(Color.parseColor("#999999"));
                    mTvBancarias.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_not_completed));
                    mTvBancarias.setTextColor(Color.parseColor("#999999"));
                } else {
                    onTabSelected(TAG_INDEX_ONE);
                    mmTvPersonales.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_complete));
                    mmTvPersonales.setTextColor(getActivity().getColor(R.color.black));
                    mTvLaborales.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_not_completed));
                    mTvLaborales.setTextColor(Color.parseColor("#999999"));
                    mTvFamiliares.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_not_completed));
                    mTvFamiliares.setTextColor(Color.parseColor("#999999"));
                    mTvBancarias.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_not_completed));
                    mTvBancarias.setTextColor(Color.parseColor("#999999"));
                }
            }
        });

    }

    public void showLoading() {
        if (loadDingDialog == null) {
            loadDingDialog = new LoadingDialog(this);
        }
        if (!loadDingDialog.isShowing() && !isFinishing()) {//如果没有显示，就要显示
            loadDingDialog.show();
        }
    }

    public void hideLoading() {
        if (loadDingDialog != null && loadDingDialog.isShowing()) {
            loadDingDialog.dismiss();
        }
    }

    @Override
    public void initData() {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            dialog_background.setVisibility(View.GONE);

        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onBackPressed() {
        LogUtils.logE("tabIndex>>>" + tabIndex);
        if (tabIndex == 3) {
//            tabIndex = 2;
//            doTab(tabIndex);
            linkCommonRententionDialog.showToRetentionDialog(CapitalInforActivity.this);
        } else if (tabIndex == 2) {
            tabIndex = 1;
            doTab(tabIndex);
        } else if (tabIndex == 1) {
            tabIndex = 0;
            doTab(tabIndex);
        } else {
            if (!TextUtils.isEmpty(from)) {
                finish();
                startActivity(MainActivity.class);
            } else {
                retentionDialog.showToRetentionDialog(CapitalInforActivity.this);
            }
        }
    }

    public void setTabIndex(int index) {
        tabIndex = index;
    }

    public void onTabSelected(int index) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                FragmentTransaction transaction = fragmentManager.beginTransaction();
                hideFragments(transaction);
                switch (index) {
                    case TAG_INDEX_ONE: {
                        headerTitle.setText("Solicitud de préstamo");
                        mmTvPersonales.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_complete));
                        mmTvPersonales.setTextColor(getActivity().getColor(R.color.black));
                        mTvSafety.setText("         Por favor, tenga la seguridad de que protegeremos su privacidad y su información estará 100% segura.");
                        if (personalInformation == null) {
                            personalInformation = new PersonalInformationFragment();
                            transaction.add(R.id.fl_base_view, personalInformation, FRAGMENTNAMEONE);
                        } else {
                            transaction.show(personalInformation);
                        }
                    }
                    break;

                    case TAG_INDEX_TWO: {
                        headerTitle.setText("Solicitud de préstamo");
                        mTvLaborales.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_complete));
                        mTvLaborales.setTextColor(getActivity().getColor(R.color.black));
                        mTvSafety.setText("         Por favor, tenga la seguridad de que protegeremos su privacidad y su información estará 100% segura.");
                        if (laboralInformation == null) {
                            laboralInformation = new LaboralInformationFragment(CapitalInforActivity.this);
                            transaction.add(R.id.fl_base_view, laboralInformation, FRAGMENTNAMETWO);
                        } else {
                            transaction.show(laboralInformation);
                        }
                    }
                    break;

                    case TAG_INDEX_THREE: {
                        headerTitle.setText("Solicitud de préstamo");
                        mTvFamiliares.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_complete));
                        mTvFamiliares.setTextColor(getActivity().getColor(R.color.black));
                        mTvSafety.setText("         Por favor, tenga la seguridad de que protegeremos su privacidad y su información estará 100% segura.");
                        if (familialInformation == null) {
                            familialInformation = new FamilialInformationFragment(CapitalInforActivity.this);
                            transaction.add(R.id.fl_base_view, familialInformation, FRAGMENTNAMETHREE);
                        } else {
                            transaction.show(familialInformation);
                        }
                    }
                    break;

                    case TAG_INDEX_FOUR: {
                        headerTitle.setText("Vincule su cuenta");//添加了中间文字的修改
                        mTvBancarias.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_complete));
                        mTvBancarias.setTextColor(getActivity().getColor(R.color.black));
                        mTvSafety.setText("         Felicitaciones, será elegible para un préstamo en poco tiempo después de completar la información a continuación.");
                        if (linkAccount == null) {
                            linkAccount = new LinkAccountFragment(CapitalInforActivity.this);
                            transaction.add(R.id.fl_base_view, linkAccount, FRAGMENTNAMEFOUR);
                        } else {
                            transaction.show(linkAccount);
                        }
                    }
                    break;
                }
                transaction.commit();
            }
        });
    }

    private void clearSelection() {

        mTvBancarias.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_not_completed));
        mTvBancarias.setTextColor(this.getResources().getColor(R.color.grey_999999));

        mTvFamiliares.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_not_completed));
        mTvFamiliares.setTextColor(this.getResources().getColor(R.color.grey_999999));

        mTvLaborales.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_not_completed));
        mTvLaborales.setTextColor(this.getResources().getColor(R.color.grey_999999));

        mmTvPersonales.setBackground(getActivity().getDrawable(R.drawable.icon_schedule_not_completed));
        mmTvPersonales.setTextColor(this.getResources().getColor(R.color.grey_999999));

    }

    private void hideFragments(FragmentTransaction transaction) {
        if (personalInformation != null) {
            transaction.hide(personalInformation);
        }
        if (laboralInformation != null) {
            transaction.hide(laboralInformation);
        }

        if (familialInformation != null) {
            transaction.hide(familialInformation);
        }

        if (linkAccount != null) {
            transaction.hide(linkAccount);
        }
    }

    @Override
    public void onStop(){
        super.onStop();
        hideLoading();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PointMgr.INSTANCE.sendEvent("cl_personal_info_exit");
        Log.e("PointMgr.INSTANCE.sendEvent","cl_personal_info_exit");

    }

    @Override
    public void sendValue(String value) {
        Log.e("----bedark","1");
        if ( value.equals("beDark") ){
            dialog_background.setVisibility(View.VISIBLE);
        } else {
            dialog_background.setVisibility(View.GONE);
        }
    }

}
